package com.ivan.toolkit.swing;

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class Images {

	
	private ImageIcon icon = null;

	public Images() {
	}

	public Images(ImageIcon icon) {
		super();
		this.icon = icon;
	}

	public ImageIcon getIcon() {
		return icon;
	}

	public void setIcon(ImageIcon icon) {
		this.icon = icon;
	}
	
	public Images scale(int width, int height, int hints) {
		
		if(icon == null)
			return this;
		
		if(icon.getIconWidth() == width && 
				icon.getIconHeight() == height) {
			return this;
		}
		
		icon = new ImageIcon(icon.getImage().getScaledInstance(width, height, hints));
		
		return this;
	}
	
	public Images scale(int width, int height) {
		
		return scale(width, height, Image.SCALE_SMOOTH);
	}
	
	public static Images loadResource(String resource) {
		return new Images(new ImageIcon(Images.class.getResource(resource)));
	}
	
	public static Images loadResource(String resource, int width, int height, int hints) {
		Images assist = loadResource(resource);
		assist.scale(width, height, hints);
		return assist;
	}
	
	public static Images loadResource(String resource, int width, int height) {
		Images assist = loadResource(resource);
		assist.scale(width, height);
		return assist;
	}
	
	public static Images attach(ImageIcon icon) {
		return new Images(icon);
	}
	
	public static Image gray(Image image) {
		
		int width = image.getWidth(null);
		while(width == -1) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {}
			width = image.getWidth(null);
		}
		
		int height = image.getHeight(null);
		
		BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);
		Graphics g = bi.getGraphics();
		g.drawImage(image, 0, 0, width, height, null);
		g.dispose();
		
		return bi;
		
	}
	
}
